var express = require('express');
var router = express.Router();
module.exports = exports = router;
var debug = require('debug')('admin');
var AdminDao = require('../../../modelDao/adminDao.js');

router.get('/list', function (req, res, next) {
    AdminDao.fetchAll().then(function (docs) {
        var result = {
            errcode: 200,
            errmsg: 'ok',
            list: docs
        };
        res.status(200).send(JSON.stringify(result));
    }, function (err) {
        var result = {
            errcode: 400,
            errmsg: err
        };
        res.status(400).send(JSON.stringify(result));
    });
});


// login
var bodyParser = require('body-parser');
router.post('/login', function (req, res, next) {
    bodyParser.json()(req, res, function () {

        var loginId = req.body.loginId; // nameOrEmail
        var password = req.body.password;
        debug('login, loginId=' + loginId + ",password=" + password);

        AdminDao.isMatch(loginId, password)
            .then(function resolve(reply) {
                debug('db return succ');
                req.session.adminId = loginId;
                res.status(reply.errcode).send(JSON.stringify(reply.errmsg));
            }, function reject(err) {
                debug('fail');
                res.status(err.errcode).send(JSON.stringify(err.errmsg));
            });
    });
});


router.get('/:id', function (req, res, next) {
    // console.log('id=' + req.params.id);
    //res.status(200).send(JSON.stringify({a:"a",b:"b"}));
    //return;

    AdminDao.findById(req.params.id).then(function (doc) {
        var result = {
            errcode: 200,
            errmsg: 'ok',
            doc: doc
        };
        res.status(200).send(JSON.stringify(result));
    }, function (err) {
        var result = {
            errcode: 400,
            errmsg: err
        };
        res.status(400).send(JSON.stringify(result));
    });
});

router.put('/:id', function (req, res, next) {
    debug('put ' + req.params.xxxId);
    res.status(200).end(req.url + " ok");
});

router.delete('/:id', function (req, res, next) {
    debug('delete ' + req.params.xxxId);
    res.status(200).end(req.url + " ok");
});
